package org.kfish.framework.helper;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.kfish.framework.util.ReflectionUtil;

public class BeanHelper {
	/**
	 * 定义 bean map(用于存储 Bean 类 与 Bean 实例 映射关系 )
	 */
	private static final Map<Class<?>,Object> BEAN_MAP = new HashMap<>();
	
	// 实例化每一个Bean
	static {
		
		Set<Class<?>> beanClassSet = ClassHelper.getBeanClassSet();		
		for(Class<?> beanClass:beanClassSet){
			Object obj = ReflectionUtil.newInstance(beanClass);
			BEAN_MAP.put(beanClass, obj);
		}	
	}
	/**
	 * 获取Bean Map
	 * @return
	 */
	public static Map<Class<?>,Object> getBeanMap(){
		return BEAN_MAP;
	}
	
	/**
	 * 根据 class 获取相应的bean
	 * @param cls
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getBean(Class<T> cls){
		if(!BEAN_MAP.containsKey(cls)){
			throw new RuntimeException("can not get bean by class: "+cls);
		}
		return (T) BEAN_MAP.get(cls);
	}
	
	public static void setBean(Class<?> cls,Object obj){
		BEAN_MAP.put(cls, obj);
	}
}
